package cn.com.dstz.admin.action;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang.StringUtils;
import org.hibernate.Hibernate;
import org.hibernate.type.Type;

import cn.com.dstz.agent.config.AdminConfig;
import cn.com.dstz.base.action.BaseAction;
import cn.com.dstz.security.encoder.Md5PwdEncoder;
import cn.com.dstz.utils.ActionUtils;
import cn.com.dstz.utils.DataBaseUtils;
import cn.com.dstz.utils.ValidUtils;
import cn.com.dstz.web.constants.Constants;

/**
 * 管理员列表
 * 
 * 当没有附加权限的时候，只查看自己的
 * 当有的时候，根据分配查看
 * 
 * 
 * 2013-5-22  20:38 完成修复
 * 2013-6-04 20:52 二次修复
 * @author 叶装装
 *
 */
public class AdminAct extends BaseAction{
	
	public void list( ){
		
		Map< String, Object > admin = this.getEntityInSession( Constants.ADMIN_IN_SESSION );
		int level = ActionUtils.getAdminLevel( admin );
		
		Map< String, Object > valueMap = null;
		
		String sql = "select a.id as id,a.telphone,a.qqnum, a.aid as aid, a.username as username, a.name as name, a.groupid as groupid, a.status as status, ag.name as agentname, g.name as groupname, a.topaid as agentid, a1.username as parentname from dstzgroup g, dstzadmin a left outer join dstzagent ag on a.topaid = ag.id left outer join dstzadmin a1 on a1.id = a.aid where a.groupid = g.id ";
		
		// 等级大于0的，就查询自己的
		if( level > 0 ){
			AdminConfig config = new AdminConfig( admin, this.countManagerGroup( ));
			sql += config.getSQL( );
			valueMap = config.getValueMap( );
	
			sql += " and a.status=:status";
			
			valueMap.put( "status", cn.com.dstz.admin.constants.Constants.ADMIN_STATUS_NORMAL );
			
		}
		
		Map< String, Type > aliasMap = DataBaseUtils.getAlias( new String[]{
				"id", "telphone","qqnum","aid" ,"username", "name", "groupid", "status", "agentname", "groupname", "agentid", "parentname"
		}, new Type[]{
				Hibernate.INTEGER, Hibernate.STRING,Hibernate.STRING,Hibernate.INTEGER, Hibernate.STRING, Hibernate.STRING, Hibernate.INTEGER, Hibernate.BYTE, Hibernate.STRING, Hibernate.STRING, Hibernate.INTEGER,
				Hibernate.STRING
		} );
		this.responseToJsonObject( this.paginationBySQL( sql, null, valueMap,  null,  aliasMap )  );
		
		return;
		
	}
	
	public String toadd( ){
		setGroupList( 0 );
		
		return "add";
	}
	
	public void add( ){
		
		Map< String, Object > admin = this.getEntityInSession( Constants.ADMIN_IN_SESSION );
		
		int validSaveOrUpdate = validSaveOrUpdate(  0 );
		
		if( validSaveOrUpdate > 0 ){
			this.ajaxResponse( validSaveOrUpdate );
			return;
		}
		
		int level = ActionUtils.getAdminLevel( admin );
		Object adminid = level == 0 ? 0 : admin.get( "id" );
		
		int save = baseService.save( "dstzadmin", DataBaseUtils.getData( new String[]{
				"username", "password", "name", "groupid", "status", "aid", "topaid","telphone","qqnum"
		}, new Object[]{
				username, password, name, groupid, getStatus( ) , adminid,  admin.get( "topaid" ),telphone,qqnum
		} ) );
		
		this.addLog( save, "admin", 0, username );
		
		this.ajaxResponse( save > 0 ? 0 : -1 );
		return;
	}
	
	public String toedit( ){
		
		int validSaveOrUpdate = validSaveOrUpdate( 2 );
		
		if( validSaveOrUpdate > 0 ){
			this.alertMsg( null );
			return "edit";
		}
		
		setGroupList( 1 );
		
		String sql = "select * from dstzadmin where id=:id";
		Map< String, Object > valueMap = new HashMap< String, Object >( );
		valueMap.put( "id", id );
		Map< String, Object > data = baseService.queryForMap( sql, valueMap );
		getRequest( ).setAttribute( "data", data );
		
		return "edit";
	}
	
	public void edit( ){
		
		int validSaveOrUpdate = validSaveOrUpdate( 1 );
		
		if( validSaveOrUpdate > 0 ){
			this.ajaxResponse( validSaveOrUpdate );
			return;
		}
		
		Map< String, Object > updateData = getUpdateData( );
		
		int update = baseService.update( "dstzadmin", updateData, DataBaseUtils.getData( new String[]{
				"id"
		}, new Object[]{
				id
		} ) );
		
		this.addLog( update, "admin", 1, "ID：" + id );
		
		this.ajaxResponse( update > 0 ? 0 : -1 );
	}
	
	public void delete( ){
		
		String ids = getParameter( "ids" );
		
		if( ids != null ){
			String [] splitIds = StringUtils.split( ids, "," );
			
			if( splitIds != null && splitIds.length > 0 ){
				List< String > updateSqlList = new ArrayList< String >( );
				
				Map< String, Object > admin = this.getEntityInSession( Constants.ADMIN_IN_SESSION );
				int level = ActionUtils.getAdminLevel( admin );
				
				for( String id : splitIds ){
					if( StringUtils.isNotBlank( id )){
						
						if( level == 0 ){
							updateSqlList.add( "delete from dstzadmin where id =" + id);
						}else{
							updateSqlList.add( "update dstzadmin set status = " + cn.com.dstz.admin.constants.Constants.ADMIN_STATUS_DISABLED + " where id =" + id + " and aid=" + admin.get( "id" )); // 只能编辑自己的
						}
					}
				}
				
				int del = baseService.saveOrUpdateBatch( updateSqlList );
				
				this.addLog( del, "admin", 2, ids );
				
			}
		}
		
	}
	
	private int validSaveOrUpdate( int saveOrUpdate ){
		// 等于2 表示是 转到编辑页面或者删除
		if( saveOrUpdate == 2 ){
			if( id == null || id == 0 ){
				return 1;
			}
			return 0;
		}
		
		if( ValidUtils.validLength( username, 3, 20 )){
			return 1;
		}
		
		// 编辑的时候可以不指定密码,所以这里的判断要修改
		if( saveOrUpdate != 1 ){
			if( StringUtils.isBlank( password )){
				return 2;
			}
		}
		
		if( ValidUtils.validLengthCanEmpty( name, 32 ) ){
			return 3;
		}
		
		if( groupid == null || groupid == 0 ){
			return 4;
		}
		
		int count = 0;
		
		if( saveOrUpdate == 0 ){
			count = dbVliad( );
		}else {
			if(! StringUtils.equals( username, oldusername ) ){
				count = dbVliad( );
			}
		}
		
		if( count > 0 ){
			return 5;
		}
		
		return 0;
	}
	
	private int dbVliad( ){
		return baseService.countBySQL( "select count(*) as a from dstzadmin where username=:username", DataBaseUtils.getData( new String[]{
				"username"
		}, new Object[]{
				username
		} ) );
	}
	
	private Map< String, Object > getUpdateData( ){
		
		Map< String, Object > updateData = new HashMap< String, Object >( );
		
		updateData.put( "username", username );
		updateData.put( "name", name );
		updateData.put( "groupid", groupid );
		updateData.put( "status", getStatus() );
		
		if( StringUtils.isNotBlank( password )){
			updateData.put( "password", password );
		}
		return updateData;
	}
	
	// 这里要查询顶级是否能查询包括自己的分组管理员
	private void setGroupList( int saveOrUpdate ){
		
		Map< String, Object > admin = this.getEntityInSession( Constants.ADMIN_IN_SESSION );
		int level = ActionUtils.getAdminLevel( admin );
		Map< String, Object > valueMap = new HashMap< String, Object >( );
		valueMap.put( "ismanager", 1 );
		
		String sql = "select * from dstzgroup g, dstz_group_type t where g.id = t.groupid and t.ismanager=:ismanager";
		
		if( level == 0 ){
			if( saveOrUpdate == 0 ){
				sql += " and t.level = :level"; // this is add
			}
			
		}else{
			sql += " and t.level >:level";
			
		}
		
		valueMap.put( "level", level );
		
		List< Map< String, Object >> groupList = baseService.queryForListByAll( sql, valueMap );
		
		getRequest( ).setAttribute( "groupList", groupList );
		
	}
	

	
	private static final long serialVersionUID = 1L;
	
	private String name;
	private String username;
	private String oldusername;
	private String password;
	private Integer groupid;
	private Integer id;
	private Integer status;
	private String telphone;
	private String qqnum;
	private Md5PwdEncoder pwdEncoder;

	public String getName( ) {
		return name;
	}

	public String getTelphone() {
		return telphone;
	}

	public void setTelphone(String telphone) {
		this.telphone = telphone;
	}

	public String getQqnum() {
		return qqnum;
	}

	public void setQqnum(String qqnum) {
		this.qqnum = qqnum;
	}

	public void setName( String name ) {
		if( StringUtils.isNotBlank( name )){
			name = decode( name );
		}
		this.name = name;
	}

	public String getUsername( ) {
		return username;
	}

	public void setUsername( String username ) {
		if( StringUtils.isNotBlank( username )){
			username = decode( username );
		}
		this.username = username;
	}

	public String getOldusername( ) {
		return oldusername;
	}

	public void setOldusername( String oldusername ) {
		if( StringUtils.isNotBlank( oldusername )){
			oldusername = decode( oldusername );
		}
		this.oldusername = oldusername;
	}

	public String getPassword( ) {
		return password;
	}

	public void setPassword( String password ) {
		if( StringUtils.isNotBlank( password )){
			password = pwdEncoder.md5( password );
		}
		this.password = password;
	}

	public Integer getGroupid( ) {
		return groupid;
	}

	public void setGroupid( Integer groupid ) {
		this.groupid = groupid;
	}

	public Integer getId( ) {
		return id;
	}

	public void setId( Integer id ) {
		this.id = id;
	}
	

	public Integer getStatus( ) {
		if( status == null ){
			status = 0;
		}
		return status;
	}

	public void setStatus( Integer status ) {
		if( status == null ){
			status = 0;
		}
		this.status = status;
	}

	public Md5PwdEncoder getPwdEncoder( ) {
		return pwdEncoder;
	}

	public void setPwdEncoder( Md5PwdEncoder pwdEncoder ) {
		this.pwdEncoder = pwdEncoder;
	}
}
